package com.syt.cellphone.information

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatDelegate
import androidx.multidex.MultiDexApplication
import com.jeremyliao.liveeventbus.LiveEventBus
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.CsvFormatStrategy
import com.orhanobut.logger.DiskLogAdapter
import com.orhanobut.logger.Logger
import com.syt.cellphone.information.constant.AppConst.CHANNEL_ID_DOWNLOAD
import com.syt.cellphone.information.constant.PreferKey
import com.syt.cellphone.information.data.AppDatabase
import com.syt.cellphone.information.help.ActivityHelp
import com.syt.cellphone.information.help.AppConfig
import com.syt.cellphone.information.help.CrashHandler
import com.syt.cellphone.information.lib.theme.ColorUtils
import com.syt.cellphone.information.lib.theme.ThemeStore
import com.syt.cellphone.information.utils.getCompatColor
import com.syt.cellphone.information.utils.getPrefInt
import com.syt.cellphone.information.utils.putPrefInt

/**
 *  @author: syt
 *  创建时间: 2020/7/31 10:44
 *  @功能   基础Application
 */
class App: MultiDexApplication() {

    /**
     * 静态代码块
     */
    companion object {
        lateinit var INSTANCE: App
            private set
        lateinit var db: AppDatabase
            private set
    }

    var versionCode = 0L
    var versionName = ""

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        // 异常管理类初始化
        CrashHandler().init(this)
        db = AppDatabase.createDatabase(this)
        packageManager.getPackageInfo(packageName, 0)?.let {
            versionCode = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                it.versionCode.toLong()
            } else {
                it.longVersionCode
            }
            versionName = it.versionName
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知id
            createChannelId()
        }
        // 为了黑夜模式
        applyDayNight()
        LiveEventBus
            .config()
            .supportBroadcast(this)
            .lifecycleObserverAlwaysActive(true)
            .autoClear(false)
        // 管理Activity
        registerActivityLifecycleCallbacks(ActivityHelp)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createChannelId() {
        (getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager)?.let {
            // 用唯一的ID创建通道对象 离线缓存
            val downloadChannel = NotificationChannel(
                CHANNEL_ID_DOWNLOAD,
                getString(R.string.channel_download),
                NotificationManager.IMPORTANCE_LOW
            )
            // 初始化channel
            // 灯
            downloadChannel.enableLights(false)
            // 振动
            downloadChannel.enableVibration(false)
            // 提示音
            downloadChannel.setSound(null, null)
            // 注册
            it.createNotificationChannel(downloadChannel)
        }
    }

    fun applyDayNight() {
        applyTheme()
        initNightMode()
    }

    /**
     * 更新主题
     */
    private fun applyTheme() {
        when {
            AppConfig.isEInkMode -> {
                ThemeStore.editTheme(this)
                    .coloredNavigationBar(true)
                    .primaryColor(Color.WHITE)
                    .accentColor(Color.BLACK)
                    .backgroundColor(Color.WHITE)
                    .bottomBackground(Color.WHITE)
                    .apply()
            }
            AppConfig.isNightTheme -> {
                val primary = getPrefInt(
                    PreferKey.cNPrimary,
                    getCompatColor(R.color.md_blue_grey_600)
                )
                val accent = getPrefInt(
                    PreferKey.cNAccent,
                    getCompatColor(R.color.md_deep_orange_800)
                )
                var background = getPrefInt(
                    PreferKey.cNBackground,
                    getCompatColor(R.color.md_grey_900)
                )
                if (ColorUtils.isColorLight(background)) {
                    background = getCompatColor(R.color.md_grey_900)
                    putPrefInt(PreferKey.cNBackground, background)
                }
                var bBackground = getPrefInt(
                    PreferKey.cNBBackground,
                    getCompatColor(R.color.md_grey_850)
                )
                if (ColorUtils.isColorLight(bBackground)) {
                    bBackground = getCompatColor(R.color.md_grey_850)
                    putPrefInt(PreferKey.cNBBackground, bBackground)
                }
                ThemeStore.editTheme(this)
                    .coloredNavigationBar(true)
                    .primaryColor(ColorUtils.withAlpha(primary, 1f))
                    .accentColor(ColorUtils.withAlpha(accent, 1f))
                    .backgroundColor(ColorUtils.withAlpha(background, 1f))
                    .bottomBackground(ColorUtils.withAlpha(bBackground, 1f))
                    .apply()
            }
            else -> {
                val primary =
                    getPrefInt(PreferKey.cPrimary, getCompatColor(R.color.md_indigo_800))
                val accent =
                    getPrefInt(PreferKey.cAccent, getCompatColor(R.color.md_red_600))
                var background =
                    getPrefInt(PreferKey.cBackground, getCompatColor(R.color.md_grey_100))
                if (!ColorUtils.isColorLight(background)) {
                    background = getCompatColor(R.color.md_grey_100)
                    putPrefInt(PreferKey.cBackground, background)
                }
                var bBackground =
                    getPrefInt(PreferKey.cBBackground, getCompatColor(R.color.md_grey_200))
                if (!ColorUtils.isColorLight(bBackground)) {
                    bBackground = getCompatColor(R.color.md_grey_200)
                    putPrefInt(PreferKey.cBBackground, bBackground)
                }
                ThemeStore.editTheme(this)
                    .coloredNavigationBar(true)
                    .primaryColor(ColorUtils.withAlpha(primary, 1f))
                    .accentColor(ColorUtils.withAlpha(accent, 1f))
                    .backgroundColor(ColorUtils.withAlpha(background, 1f))
                    .bottomBackground(ColorUtils.withAlpha(bBackground, 1f))
                    .apply()
            }
        }
    }

    private fun initNightMode() {
        val targetMode =
            if (AppConfig.isNightTheme) {
                AppCompatDelegate.MODE_NIGHT_YES
            } else {
                AppCompatDelegate.MODE_NIGHT_NO
            }
        AppCompatDelegate.setDefaultNightMode(targetMode)
    }

    private fun intLogger() {
        Logger.addLogAdapter(DiskLogAdapter(CsvFormatStrategy.newBuilder().build()))
        Logger.addLogAdapter(AndroidLogAdapter())
    }
}